#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Lee
# @File    : dhy_online_dis_view.py
# @Time    : 2024/1/26 15:12
from util.common_calc import *
from util.global_config import *
from PyQt5.QtWidgets import QWidget
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from views.alert_messagebox_view import show_message_box
from util.get_localization_points import GetLocalizationPoints
from views.resource_view.online_offset_view import Ui_DHYOnlineOffset
from views.dhy_connect_row_matplotlib_view import ConnectRowMplWidget


class DHYOnlineDisView(QWidget, Ui_DHYOnlineOffset):
    def __init__(self, parent=None):
        super(DHYOnlineDisView, self).__init__(parent)
        self.setupUi(self)

        # 监听测试类别
        self.ABLine.clicked.connect(lambda: self.set_test_type("ab_line"))
        self.APlusLine.clicked.connect(lambda: self.set_test_type("a_plus_line"))

        self.baseLineOffsetSpinBox.textChanged.connect(self.draw_base_line)

        # 添加matplotlib视图
        matplotlib_widget = ConnectRowMplWidget(self)
        self.matplotlib_layout.addWidget(matplotlib_widget)
        self.matplotlib_view = matplotlib_widget.qCanvas

        self.csv_file_path = ""
        self.matplotlib_view_points = None
        self.start_point_index = 0

        self.load_data_btn.clicked.connect(self.select_csv_file)
        self.redraw_line_btn.clicked.connect(self.draw_base_line)
        self.start_test_btn.clicked.connect(self.start_online_dis_test)

        self.set_test_type("ab_line")

    # 修改测试类别，AB线时角度模块置灰；A+线时B点坐标模块置灰
    def set_test_type(self, test_type):
        if test_type == "ab_line":
            self.ABLine.setChecked(True)
            self.angle_group.setEnabled(False)
            self.point_b_group.setEnabled(True)
        elif test_type == "a_plus_line":
            self.APlusLine.setChecked(True)
            self.angle_group.setEnabled(True)
            self.point_b_group.setEnabled(False)
            self.point_a_x_text.setText(a_p_x)
            self.point_a_y_text.setText(a_p_y)
            self.angle_text.setText(theta)
            self.angle_dis_text.setText(theta_offset)

        if self.csv_file_path:
            self.draw_base_line()

    @QtCore.pyqtSlot()
    def select_csv_file(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        self.csv_file_path, _ = QtWidgets.QFileDialog.getOpenFileName(None, "QFileDialog.getOpenFileName()", "",
                                                                      "CSV Files (*.csv)", options=options)
        self.load_trajectory_points_data()

    def load_trajectory_points_data(self):
        self.matplotlib_view_points = self.matplotlib_view.load_data_with_csv_file_path(self.csv_file_path)
        if self.matplotlib_view_points:
            self.point_a_x_text.setText(a_x)
            self.point_a_y_text.setText(a_y)
            self.point_b_x_text.setText(b_x)
            self.point_b_y_text.setText(b_y)
            if len(self.matplotlib_view_points[0]) > 4:
                self.angle_text.setText(str(round(self.matplotlib_view_points[0][3], 6)))
            self.draw_base_line()

    def get_clicked_index(self, index):
        _clicked_point = self.matplotlib_view_points[index]
        _dis = get_distance_of_two_point(_clicked_point, self.matplotlib_view_points[0])
        _title = "设置评价起始点"
        _text = f"当前点与驻车点的距离为:【{round(_dis, 2)}】米,是否将改点设置为评价起始点？"
        _btn_text_list = ["确定", "取消"]
        clicked_btn = show_message_box(_title, _text, _btn_text_list)

        if "确定" in clicked_btn:
            self.start_point_index = index
            self.start_to_stop_point_dis_text.setText(str(round(_dis, 2)))

    @QtCore.pyqtSlot()
    def offset_value_changed(self):
        print(self.baseLineOffsetSpinBox.text())

    @QtCore.pyqtSlot()
    def draw_base_line(self):
        _point_a = [float(self.point_a_x_text.text()), float(self.point_a_y_text.text())]
        _point_b = [0, 0]
        if self.ABLine.isChecked():  # 测试类型为AB线
            _point_b = [float(self.point_b_x_text.text()), float(self.point_b_y_text.text())]
            # self.matplotlib_view.update_line([[_point_a[0], _point_b[0]],
            #                                   [_point_a[1], _point_b[1]]], "ab_line")
        elif self.APlusLine.isChecked():
            _angle = float(self.angle_text.text()) + float(self.angle_dis_text.text()) * math.pi / 180
            # 判断起始点大小，确认行驶方向
            _start_point, _end_point = self.matplotlib_view_points[0], self.matplotlib_view_points[-1]
            _point_b = get_virtual_point(_point_a, _start_point, _end_point, _angle)
            # self.matplotlib_view.update_line([[_point_a[0], _point_b[0]],
            #                                   [_point_a[1], _point_b[1]]], "ab_line")
        _a, _b = get_offset_points(_point_a, _point_b, float(self.baseLineOffsetSpinBox.text()) / 100)
        self.matplotlib_view.update_line([[_a[0], _b[0]],
                                          [_a[1], _b[1]]], "ab_line")
    @QtCore.pyqtSlot()
    def start_online_dis_test(self):
        # 从驻车点行驶5m后作为评价起始点
        # 计算沿导航线方向持续行驶6m（法规要求大于5m）距离
        # 横向偏移误差的绝对值小于2.5m
        _start_point = self.matplotlib_view_points[0]
        _calc_index = self.start_point_index
        if _calc_index == 0:
            for index, point in enumerate(self.matplotlib_view_points):
                if get_distance_of_two_point(_start_point, point) > float(self.start_to_stop_point_dis_text.text()):
                    _calc_index = index
                    break
        if _calc_index == 0:
            QMessageBox.warning(self, "警告", f"确认当前轨迹长度大于【{self.start_to_stop_point_dis_text.text()}】米")

        _calc_points = list()
        _start_calc_point = self.matplotlib_view_points[_calc_index]
        for index in range(_calc_index, len(self.matplotlib_view_points)):
            if get_distance_of_two_point(_start_calc_point, self.matplotlib_view_points[index])\
                    > float(self.trajectory_dis_text.text()):
                break
            else:
                _calc_points.append(self.matplotlib_view_points[index])

        # 绘制竖线
        self.matplotlib_view.update_line([[_calc_points[0][0], _calc_points[0][0]],
                                          [_calc_points[0][1] + 20, _calc_points[0][1] - 20]],
                                         "left_line")
        self.matplotlib_view.update_line([[_calc_points[-1][0], _calc_points[-1][0]],
                                          [_calc_points[-1][1] + 20, _calc_points[-1][1] - 20]],
                                         "right_line")

        _x_points = self.matplotlib_view.ab_line.get_xdata()
        _y_points = self.matplotlib_view.ab_line.get_ydata()
        _point_a = [_x_points[0], _y_points[0]]
        _point_b = [_x_points[1], _y_points[1]]

        a, b, c = calc_baseline_equation(_point_a, _point_b)
        # 按照平分轨迹的方式将轨迹50等分
        _obj = GetLocalizationPoints([_point_a, _point_b], 0, None, aver_nums=global_config["aver_count"])
        _aver_points = _obj.get_aver_point("ave_trajectory", _calc_points,
                                           list(), a, b, c, True)
        _res = _obj.start_calc("ab_line")
        print(_res)
        _dis_list = [get_distance_of_point_to_line(point, a, b, c) for point in _calc_points]
        QMessageBox.information(self, "提示", f"横向偏移误差最大值为: {round(max(_dis_list) * 100, 2)} cm")
